// pages/seller/edit.js
const app = getApp();
   
let req = require('../../utils/request.js');
let api = require('../../utils/api.js');
let area = require('../../utils/area.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showModalStatus: false,
    disabled: 'disabled',
    display: 'inline-block',
    phone_country: '中国',
    phone_reg: '+86',
    index1: 0,
    range: [[
      '00','01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23'
    ], [
      '00','05','10','15','20','25','30','35','40','45','50','55'
    ]]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _this = this,
      area_arr = area.phone_reg,
      reg = [], areas = [], area_code = []
    wx.showLoading({
      title: '加载商户信息',
    })
    req.request(
      api.getSellerEditInfo,
      {method: 'POST', data: {'seller_token': app.globalData.userInfo.user_token}},
      function(res) {
        res = res.data
        if(res.status == -1) {
          wx.showToast({
            title: res.msg,
            icon: 'none'
          })
          return false;
        }

        //分割展示图
        var info = res.seller_info,
            pics = info.seller_show_pic,
            pics = pics.split(';'),
            length = pics.length,
            pics_arr = [],
            //分割营业时间
            time = info.seller_time,
            time = time.split(' - '),
            time_1 = time[0].split(':'),
            time_2 = time[1].split(':'),
            time_arr = [[time_1[0], time_1[1]], [time_2[0], time_2[1]]]
        
        for (var i in pics) {
          if (i < length - 1) {
            pics_arr.push(pics[i])
          }
        }

        //格式化国家地区
        for (var i in area_arr) {
          var arr = i.split('-')
          areas.push(arr[1])
          area_code.push(arr[2])
          reg.push(area_arr[i])
        }

        _this.setData({ reg: reg, areas: areas, area_code: area_code });
        _this.setData({ seller_info: info, pics: pics_arr, info_input: info, time: time_arr, })
        wx.hideLoading();
      }
    )
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  },
  bindPickerChange: function (e) {
    var _this = this,
      index1 = e.detail.value,
      areas = _this.data.areas,
      area_code = _this.data.area_code
      //area = '+' + area_code[index] + '  ' + areas[index]
    
    _this.setData({ 'phone_country': areas[index1], 'phone_reg':'+' + area_code[index1], index1: index1 })
    
  },
  checkLegal(e) {
    var _this = this,
        value = e.detail.value,
        index = e.currentTarget.dataset.index,
        data = {},
        pics = _this.data.pics,
        phone,fixed_phone,address,
        index1 = _this.data.index1

    switch(index) {
      case '0':
        var reg = _this.data.reg[index1]
        if(reg.test(value)) {
          data['checked_0'] = 'http://p1gruod0l.bkt.clouddn.com/20180607000920729.png'
          data['info_input.seller_phone'] = value
        }else {
          data['checked_0'] = 'http://p1gruod0l.bkt.clouddn.com/20180607000920616.png'
          data['info_input.seller_phone'] = false
        }
        break;
      case '1':
        var reg = /^\d{7,8}$/
        if (reg.test(value)) {
          data['checked_1'] = 'http://p1gruod0l.bkt.clouddn.com/20180607000920729.png'
          data['info_input.seller_fixed'] = value
        } else {
          data['checked_1'] = 'http://p1gruod0l.bkt.clouddn.com/20180607000920616.png'
          data['info_input.seller_fixed'] = false
        }
        break;
      case '2':
        var length = value.length
        if(length > 10) {
          data['checked_2'] = 'http://p1gruod0l.bkt.clouddn.com/20180607000920729.png'
          data['info_input.seller_address'] = value
        } else {
          data['checked_2'] = 'http://p1gruod0l.bkt.clouddn.com/20180607000920616.png'
          data['info_input.seller_address'] = false
        }
        break;
    }
    _this.setData(data);
    var phone_reg = this.data.phone_reg 
    phone = _this.data.info_input.seller_phone
    fixed_phone = _this.data.info_input.seller_fixed
    address = _this.data.info_input.seller_address
    if (phone != false && fixed_phone !=false && address != false) data['disabled'] = ''
    else data['disabled'] = 'disabled'

    var phoneNumber = phone_reg + phone
    _this.setData({ disabled: data['disabled'], 'info_input.seller_phone': phoneNumber}) 

    //检测图片数量
    if (pics.length >= 9) _this.setData({ display: 'none' })
      else if (pics.length == 0) _this.setData({ display: 'inline-block', disabled: 'disabled' })
      else _this.setData({ display: 'inline-block' })
  },
  changeTime(e) {
    var _this = this,
        value = e.detail.value,
        index = e.currentTarget.dataset.index,
        range = _this.data.range,
        time = _this.data.time,
        pics = _this.data.pics

    time[index][0] = range[0][value[0]]
    time[index][1] = range[1][value[1]]

    var time_string = time[0][0] + ':' + time[0][1] + ' - ' + time[1][0] + ':' + time[1][1]
    
    _this.setData({time: time, disabled: '', 'info_input.seller_time': time_string})
    //检测图片数量
    if (pics.length >= 9) _this.setData({ display: 'none' })
      else if (pics.length == 0) _this.setData({ display: 'inline-block', disabled: 'disabled' })
      else _this.setData({ display: 'inline-block' })
  },
  uploadPic(e) {
    var _this = this
    wx.chooseImage({
      success: function(res) {
        wx.showLoading({
          title: '正在上传'
        })

        var file = res.tempFilePaths,
          length = res.tempFilePaths.length
        req.uploadMulti(
          api.uploadPic,
          {
            filePath: file,
            name: 'file'
          },
          0, 0, 0, length,
          function (res, index) {
            if (index == length) {
              wx.hideLoading();
            }
            var result = JSON.parse(res.data);

            if (result.code > 0) {
              var pics = _this.data.pics,
                  pics_string = ''
              pics.push(result.pic_path)
              for(var i in pics) {
                pics_string += pics[i] + ';'
              }
              
              //检测图片数量
              if (pics.length >= 9) _this.setData({ display: 'none' })
                else if (pics.length == 0) _this.setData({ display: 'inline-block', disabled: 'disabled' })
                else _this.setData({ display: 'inline-block' })

              _this.setData({pics, pics, 'disabled': '', 'info_input.seller_show_pic': pics_string})

            }
          }
        );
      },
    })
  },
  showModal: function (e) {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })


    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true,
      currentPic: e.currentTarget.dataset.current
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },
  preview() {
    var _this = this,
        currentPic = _this.data.currentPic,
        pics = _this.data.pics
    wx.previewImage({
      current: currentPic,
      urls: pics,
    })
    _this.hideModal();
  },
  update() {
    var _this = this,
      currentPic = _this.data.currentPic,
      pics = _this.data.pics

    wx.chooseImage({
      success: function (res) {
        wx.showLoading({
          title: '正在上传'
        })

        var file = res.tempFilePaths,
          length = res.tempFilePaths.length
        req.uploadMulti(
          api.uploadPic,
          {
            filePath: file,
            name: 'file'
          },
          0, 0, 0, length,
          function (res, index) {
            if (index == length) {
              wx.hideLoading();
            }
            var result = JSON.parse(res.data);

            if (result.code > 0) {
              var pics_string = ''
              pics[currentPic] = result.pic_path
              for (var i in pics) {
                pics_string += pics[i] + ';'
              }
              
              //检测图片数量
              if (pics.length >= 9) _this.setData({ display: 'none' })
                else if (pics.length == 0) _this.setData({ display: 'inline-block', disabled: 'disabled' })
                else _this.setData({ display: 'inline-block' })

              _this.setData({ pics, pics, 'info_input.seller_show_pic': pics_string })
              _this.hideModal();
            }
          }
        );
      },
    })
  },
  deletePic() {
    var _this = this,
      currentPic = _this.data.currentPic,
      pics = _this.data.pics,
      pics_string = ''
    pics.splice(currentPic, 1)
    for (var i in pics) {
      pics_string += pics[i] + ';'
    }
    
    //检测图片数量
    if (pics.length >= 9) _this.setData({ display: 'none' })
      else if(pics.length == 0) _this.setData({ display: 'inline-block', disabled: 'disabled' })
      else _this.setData({ display: 'inline-block' })
    
    _this.setData({ pics, pics, 'info_input.seller_show_pic': pics_string })
    _this.hideModal();
  },
  submit() {
    var _this = this,
        data = _this.data.info_input
    
    data['seller_token'] = app.globalData.userInfo.user_token

    req.request(
      api.updateSellerInfo,
      {method: 'POST', data: data},
      function(res) {
        res = res.data
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
        
        if(res.status == 1) {
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            })
          }, 2000)
        }
      }
    )
  }
})